/*
 //两种调用方式
 var template1="我是{0}，今年{1}了";
 var template2="我是{name}，今年{age}了";
 var result1=template1.format("loogn",22);
 var result2=template1.format({name:"loogn",age:22});
 //两个结果都是"我是loogn，今年22了"
 */
String.prototype._format = function (args) {
    if (arguments.length > 0) {
        var result = this;
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                var reg = new RegExp("({" + key + "})", "g");
                result = result.replace(reg, args[key]);
            }
        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] == undefined) {
                    return "";
                } else {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
        return result;
    } else {
        return this;
    }
};

/*
 * 方法:Array.remove(dx) 通过遍历,重构数组 功能:删除数组元素. 参数:dx删除元素的下标.
 */
Array.prototype._remove = function (dx) {
    if (isNaN(dx) || dx > this.length) {
        return false;
    }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i];
        }
    }
    this.length -= 1;
};
/*
 * 方法:Array.remove(val) 通过遍历,重构数组 功能:删除数组元素. 参数:val删除元素的值.
 */
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};


returnstring = function (url) {

    var t = "";
    $.ajax({
        async: false,
        type: "GET",
        dataType: "text",
        url: url + '?t=' + jst,
        data: {},
        success: function (msg) {
            t = msg;

        }
    });
    return t;
};
var jst = new Date().getTime();
Date.prototype._format = function (format) // yyyy-MM-dd hh:mm:ss

{

    var o = {

        "M+": this.getMonth() + 1, // month

        "d+": this.getDate(), // day

        "h+": this.getHours(), // hour

        "m+": this.getMinutes(), // minute

        "s+": this.getSeconds(), // second

        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter

        "S": this.getMilliseconds()
        // millisecond

    };

    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1,

            (this.getFullYear() + "").substr(4 - RegExp.$1.length));

    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))

            format = format.replace(RegExp.$1,

                RegExp.$1.length == 1 ? o[k] :

                    ("00" + o[k]).substr(("" + o[k]).length));

    return format;

};

var jst = new Date().getTime();

String.prototype._trim = function () {
    var str = this;
    return str.replace(/(^\s*)|(\s*$)/g, "");
};


encodeURI_ext = function (str) {
    return encodeURIComponent(str);
    // return encodeURI(str);
};
// input 只能输入数字
checkNumVal = function (me) {
    var val = me.value;

    if (isNaN(val)) {
        me.value = "0";
    }
    if (val._trim() == "") {
        me.value = "0";
    }
};


//时间戳转时间
timestampToDatetime = function (v) {
    if (v == null)
        return "";
    if (v == "")
        return "";
    var date = new Date(v);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate() ) + ' ';
    h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;

};

timestampToDatetime_ymd = function (v) {
    if (v == null)
        return "";
    if (v == "")
        return "";
    var date = new Date(v);
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate() ) + ' ';
    h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D;

};

//对象合并
mergeJsonObject = function (jsonbject1, jsonbject2) {
    var resultJsonObject = {};
    for (var attr in jsonbject1) {
        resultJsonObject[attr] = jsonbject1[attr];
    }
    for (var attr in jsonbject2) {
        resultJsonObject[attr] = jsonbject2[attr];
    }

    return resultJsonObject;
};
//选择框全选、取消
all_check = function (me, targetName) {
    var target = "input[name='" + targetName + "']";
    if ($(me).prop("checked") == true) { //check all
        $(target).each(function () {
            $(this).prop("checked", true);
        });
    } else {
        $(target).each(function () {
            $(this).prop("checked", false);
        });
    }
};

//校验手机号
function checkMobile(str) {
    var re = /^1\d{10}$/;
    if (re.test(str)) {
        return true;
    } else {
        return false;
    }
}

//获取图像url
function getWeiXinImageUrl(url, type) {
    if (url == null || url == undefined || url == '') {
        return '';
    }

    var array = url.split("/");
    var target = array[array.length - 1];
    if (target == "") {
        return url + type;
    }

    return url.substring(0, url.lastIndexOf("/") + 1) + type;
}

// input 只能输入数字
checkNumVal = function (me) {
    var val = me.value;

    if (isNaN(val)) {
        me.value = "0";
    }
    if (val._trim() == "") {
        me.value = "0";
    }
};
// input 只能输入整形
checkNumVal_int = function (me) {

    if (event.keyCode != 37 && event.keyCode != 39) {
        if (!/^\d+$/ig.test(me.value)) {
            me.value = '';
            return;
        }
    }
    //去掉前面的0
    me.value = me.value.replace(/\b(0+)/gi, "");
};

// 获取url参数集合字符串
getUriPmStr = function () {
    var v = window.location.href;
    var strs = v.split("?");
    if (strs.length > 1) {
        return strs[1];
    } else {
        return "";
    }
};

//获取url参数
function getQueryString(url, name) {

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var tmp = url.split("?")[1];
    var r = tmp.match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/**
 * 获取url中paramName参数的值
 * @param {string} url
 * @param {string} paramName
 * @returns {null}/{string} paramValue
 */
getUrlParamValue = function (url, paramName) {
    var t = url.split('?');
    if (t.length > 1) {
        var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
        var r = url.split("?")[1].match(reg);
        if (r != null) return decodeURIComponent(r[2]);
    }
    return null;
};

/**
 * 针对url设置参数,如果url中有此参数,则修改此参数。如果url中无此参数,则新增此参数。
 * @param url
 * @param paramName
 * @param paramValue
 * @returns {string} url 设置参数后的url
 */
setUrlParam = function (url, paramName, paramValue) {
    var t = url.split('?');
    url = t[0];
    if (t.length > 1) {
        var pString = t[1];
        if (pString.length > 0) {
            var params = pString.split('&');
            var hasParam = false;
            for (var i = 0; i < params.length; i++) {
                var param = params[i].split('=');
                var pName = param[0];
                var pValue = param[1];
                if (i == 0) {
                    url += '?';
                } else {
                    url += '&';
                }
                url += pName + '=';
                if (pName == paramName) {
                    hasParam = true;
                    url += paramValue;
                } else {
                    url += pValue;
                }
            }
            if (!hasParam) {
                url += '&' + paramName + '=' + paramValue;
            }
        } else {
            url += '?' + paramName + '=' + paramValue;
        }
    } else {
        url += '?' + paramName + '=' + paramValue;
    }

    return url;
};

/**
 * 移除url中的某个参数
 * @param url
 * @param paramName
 * @returns {string} url 移除参数后的url
 */
removeUrlParam = function (url, paramName) {
    var t = url.split('?');
    url = t[0];
    if (t.length > 1) {
        var pString = t[1];
        if (pString.length > 0) {
            var params = pString.split('&');
            var pCount = 0;
            for (var i = 0; i < params.length; i++) {
                var pName = params[i].split('=')[0];
                if (pName != paramName) {
                    if (pCount == 0) {
                        url += '?';
                    } else {
                        url += '&';
                    }
                    pCount++;
                    url += params[i];
                }
            }
        }
    }

    return url;
};

/**
 * 移除url中的所有参数
 * @param url
 * @returns {string} url 移除参数后的url
 */
removeUrlAllParams = function (url) {
    return url.split('?')[0];
}

requestJson = function (url, data, async, successFun, errorFun) {
    if (!(typeof loading == 'undefined')) {
        loading.show();
    }

    var responseData = {};
    responseData.status = -100;
    responseData.message = '网络不给力!';
    responseData.data = null;

    // data._csrf = $('meta[name="csrf-token"]').attr("content");

    $.ajax({
        async: async || false,
        type: "POST",
        url: url + "?t=" + jst,
        data: data,
        dataType: "json",
        success: function (data) {
            responseData = data;

            if (successFun) {
                successFun(data);
            }

            if (!(typeof loading == 'undefined')) {
                loading.hide();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (!(typeof loading == 'undefined')) {
                loading.hide();
            }

            responseData.status = -101;
            responseData.message = XMLHttpRequest.responseText;

            errorMessage(responseData.message);

            if (errorFun) {
                errorFun(responseData);
            }
        }
    });

    return responseData;
};
requestJsonMallM = function (url, data, async, successFun, errorFun) {
    if (!(typeof loading == 'undefined')) {
        loading.show();
    }

    var responseData = {};
    responseData.status = -100;
    responseData.message = '网络不给力!';
    responseData.data = null;

    // data._csrf = $('meta[name="csrf-token"]').attr("content");

    $.ajax({
        async: async || false,
        type: "POST",
        url: url + "?t=" + jst,
        data: data,
        dataType: "json",
        success: function (data) {
            responseData = data;
            if (typeof responseData != "object") {
                responseData = {};
                responseData.status = -4444;
                responseData.message = data;
            }
            if (responseData.status == -1) {
                window.location.href = responseData.data.loginUrl;
                responseData = null;
            }
            if (successFun) {
                successFun(data);
            }

            if (!(typeof loading == 'undefined')) {
                loading.hide();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (!(typeof loading == 'undefined')) {
                loading.hide();
            }

            responseData.status = -101;
            responseData.message = XMLHttpRequest.responseText;

            errorMessage(responseData.message);

            if (errorFun) {
                errorFun(responseData);
            }
        }
    });

    return responseData;
};
requestHtml = function (url, data, async, successFun, errorFun) {
    var responseHtml = null;

    $.ajax({
        async: async || false,
        type: "POST",
        url: url,
        data: data,
        dataType: "html",
        success: function (data) {
            responseHtml = data;

            if (successFun) {
                successFun(data);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            responseHtml = XMLHttpRequest.responseText;

            errorMessage(responseHtml);

            if (errorFun) {
                errorFun(responseHtml);
            }
        }
    });

    return responseHtml;
};

compareDate = function (d1, d2) {
    return ((new Date(d1.replace(/-/g, "\/"))) < (new Date(d2.replace(/-/g, "\/"))));
};


errorMessage = function (message) {
    var errorDialog = $('#errorModal');
    if (errorDialog.length > 0) {
        $('#errorContainer').html(message);
        $('#errorModal').modal('show');
    } else {
        alert(message);
    }
};

//判断是否在微信内
function is_weixin() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}


//更新下级机构数据对话框
function updateChildInstData(url, institution_code, type) {
    if (institution_code == null || institution_code == '') {
        alert("机构信息不能为空！");
        return;
    }
    if (type == null || type == '') {
        alert("操作类别不能为空！");
        return;
    }
    //调用取得选择机构的下级机构
    var data = {};
    data.institution_code = institution_code;
    data.type = type;
    $("#updateChild_SuperInstCode").val('');
    $("#childInstList").html('');
    requestHtml(url, data, true, function (responseHtml) {
        $("#updateChild_SuperInstCode").val(institution_code);
        $("#childInstList").html(responseHtml);
    });
    //显示对话框
    $('#modalChildInstList').modal('show');
}

//确定更新下级机构数据
function confUpdateChildInstData(url, type) {
    //取得选择的下级机构列表
    var childInstCodeList = [];
    $("input:checkbox[name=clildInstlist]:checked").each(function () {
        childInstCodeList.push($(this).data('child-institution-code'));
    });
    var superInstCode = $("#updateChild_SuperInstCode").val();

    if (childInstCodeList != null && childInstCodeList.length > 0) {
        //更新下级机构产品数据操作--->
        var data = {};
        data.super_institution_code = superInstCode;
        data.institution_code_list = childInstCodeList;
        data.type = type;

        requestJson(url, data, true, function (response) {
            if (response.status == 0) {
                alert('操作成功！');
                //关闭对话框
                $('#modalChildInstList').modal('hide');
            } else {
                alert(response.message);
            }
        });
    } else {
        alert("请选择机构！");
    }
}


function PreviewImage(file, prevDiv, w, h) {
    if (file.files && file.files[0]) {
        var reader = new FileReader();
        reader.onload = function (evt) {
            prevDiv.append('<div class="tag-img-item upload-img-show"><img id="img_n' + n + '" src="' + evt.target.result + '" style="width: 400px;" /></div>');
            setTimeout(function () {
                initMany(w, h);
            }, 500);
        };

        reader.readAsDataURL(file.files[0]);
    }
    else {
        prevDiv.append('<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>');
    }

}